package com.qssoft.cqry.synchdb.handler;

import com.alibaba.fastjson.JSON;
import com.qssoft.cqry.synchdb.adapter.MysqlBinlogPositionAdapter;
import com.qssoft.cqry.synchdb.properties.SynchDbProperties;
import com.qssoft.cqry.synchdb.vo.BinlogPositionVo;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 设置数据库日志文件标记
 * @author liju.z
 */
public class MysqlBinlogPositionHandler implements MysqlBinlogPositionAdapter {

    private RedisTemplate<String, Object> redisTemplate;

    private String applicationName;

    private String binlogPositionKey = "mysqlBinlog:position:";

    private SynchDbProperties.SynchMysqlProperties synchMysqlProperties;

    public MysqlBinlogPositionHandler(RedisTemplate<String, Object> redisTemplate, String applicationName, SynchDbProperties.SynchMysqlProperties synchMysqlProperties) {
        this.redisTemplate = redisTemplate;
        this.applicationName = applicationName;
        this.synchMysqlProperties = synchMysqlProperties;
    }

    private String getMysqlBinloPositionKey(){
        return binlogPositionKey + applicationName + ":" + synchMysqlProperties.getIp() + ":" + synchMysqlProperties.getServerId();
    }

    @Override
    public BinlogPositionVo getBinlogPositionVo() {
        Object obj = redisTemplate.opsForValue().get(getMysqlBinloPositionKey());
        return JSON.parseObject(JSON.toJSONString(obj), BinlogPositionVo.class);
    }

    @Override
    public void binlogPositionHandler(BinlogPositionVo binlogPositionVo) {
        System.out.println(getMysqlBinloPositionKey());
        redisTemplate.opsForValue().set(getMysqlBinloPositionKey(), binlogPositionVo);
    }
}
